<template>
  <el-form :model="form" :rules="rules" ref="ruleForm" label-position="top">
    <el-form-item label="账号" prop="username">
      <el-input v-model="form.username" clearable></el-input>
    </el-form-item>
    <el-form-item label="密码" prop="passwd">
      <el-input
        type="password"
        v-model="form.passwd"
        autocomplete="off"
        show-password
      ></el-input>
    </el-form-item>
    <el-form-item label="确认密码" prop="checkPasswd">
      <el-input
        type="password"
        v-model="form.checkPasswd"
        autocomplete="off"
        show-password
      ></el-input>
    </el-form-item>
    <el-form-item>
      <el-button
        :style="{ width: '100%' }"
        type="primary"
        :loading="isSubmit"
        @click="onSubmit()"
        >{{ infoText }}</el-button
      >
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  data() {
    const validateUsername = async (rule, value, cb) => {
      try {
        const res = await this.$api.getUser(value)
        if (res.user) {
          cb(new Error('用户名已存在！'))
        }
      } catch (err) {
        console.log(err)
      }
      cb()
    }

    const validatePasswd = (rule, value, cb) => {
      if (/^(\d+)$|^([a-zA-Z]+)$/.test(value)) {
        cb(new Error('请不要只使用数字、字母，至少需包含两种字符'))
      } else {
        cb()
      }
    }

    const validateCheckPasswd = (rule, value, cb) => {
      if (value !== this.form.passwd) {
        cb(new Error('两次输入的密码不一致！'))
      } else {
        cb()
      }
    }
    return {
      isSubmit: false,
      infoText: '注册',
      form: {
        username: '',
        passwd: '',
        checkPasswd: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名！', trigger: 'blur' },
          {
            min: 3,
            max: 20,
            message: '请保持长度为 3~20 个字符',
            trigger: 'blur'
          },
          {
            pattern: /^\w+$/,
            message: '只能使用数字、大小写字母和下划线！',
            trigger: 'blur'
          },
          { validator: validateUsername, trigger: 'blur' }
        ],
        passwd: [
          { required: true, message: '请输入密码！', trigger: 'blur' },
          {
            min: 6,
            max: 20,
            message: '请保持长度为 6~20 个字符',
            trigger: 'blur'
          },
          { validator: validatePasswd, trigger: 'blur' }
        ],
        checkPasswd: [
          { required: true, message: '请再次输入密码！', trigger: 'blur' },
          { validator: validateCheckPasswd, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    onSubmit() {
      this.isSubmit = true
      this.infoText = '正在提交注册信息...'
      this.$refs['ruleForm'].validate(async valid => {
        if (valid) {
          try {
            await this.$api.signup({
              username: this.form.username,
              passwd: this.form.passwd
            })
            this.$notify({
              title: '注册成功！',
              type: 'success'
            })
            // todo: 自动登录，并跳转到之前访问页面
            this.infoText = '注册成功！正在为您跳转到之前页面...'
            await this.$api.login({
              username: this.form.username,
              passwd: this.form.passwd
            })
            this.$router.push('/')
            console.log('注册后自动登录！')
          } catch (error) {
            this.$message({
              type: 'error',
              message: '未知错误！'
            })
          }
        } else {
          this.$message({
            type: 'error',
            message: '请先完成验证！'
          })
        }
        this.isSubmit = false
      })
    }
  }
}
</script>
